import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useRef, useState } from 'react';
import type { CreateUserProps } from './components/CreateUserDrawer';
import CreateUserDrawer from './components/CreateUserDrawer';
import InviteFriendForm from './components/InviteFriendForm';
import { dyCpsUserRegister, dyCpsUsers } from './service';

const handleSaveUser = async (selectedRows: CreateUserProps) => {
  const hide = message.loading('正在更新');
  try {
    await dyCpsUserRegister({ ...selectedRows });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败');
    return false;
  }
};

const statusText = {
  1: {
    text: '使用中',
    status: 'Success',
  },
  0: {
    text: '停用',
    status: 'Error',
  },
};
const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [requestStatus] = useState(currentUser?.userInfo?.role !== 'super');
  const actionRef = useRef<ActionType>();
  const [userFormType, handleUserFormType] = useState<number>(0);
  const [createUserVisible, handleCreateUserVisible] = useState<boolean>(false);
  const [currentClueRow, setCurrentClueRow] = useState<CreateUserProps>();
  const [inviteId, setInviteId] = useState<string>('');
  const [inviteIdVisible, setInviteIdVisible] = useState<boolean>(false);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const userRole = [
    {
      label: '超管',
      value: 'super',
    },
    {
      label: '管理员',
      value: 'admin',
    },
    {
      label: '渠道用户',
      value: 'normal',
    },
  ];
  const cpsConf = [
    {
      label: 'APP_TEST',
      value: 'CPS-ZBJ-yf',
    },
    {
      label: 'APP',
      value: 'CPS-ZBJ-yf2',
    },
    {
      label: 'APP_3',
      value: 'CPS-ZBJ-yf3',
    },
    {
      label: 'APP_4',
      value: 'CPS-ZBJ-yf4',
    },
    {
      label: 'APP_5',
      value: 'CPS-ZBJ-yf5',
    },
  ];
  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'nickname',
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      copyable: true,
    },
    {
      title: '角色',
      dataIndex: 'role',
      valueType: 'select',
      hideInSearch: requestStatus,
      request: async () => {
        return userRole;
      },
    },
    {
      title: '渠道',
      dataIndex: 'extData',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        return cpsConf;
      },
    },
    {
      title: '联系渠道',
      dataIndex: 'channel',
      hideInSearch: true,
    },
    {
      title: '微信号',
      dataIndex: 'wechat',
      hideInSearch: true,
    },
    {
      title: '支付宝实名',
      dataIndex: 'zfbName',
      hideInSearch: true,
    },
    {
      title: '支付宝账号',
      dataIndex: 'zfbAcount',
      hideInSearch: true,
    },
    {
      title: '银行卡开户行',
      dataIndex: 'bankName',
      hideInSearch: true,
    },
    {
      title: '银行卡开户支行',
      dataIndex: 'bankUserName',
      hideInSearch: true,
    },
    {
      title: '银行卡账号',
      dataIndex: 'bankNum',
      hideInSearch: true,
    },
    {
      title: '账户',
      dataIndex: 'account',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: statusText,
    },
    {
      title: '用户注册时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <a
          key="editable"
          onClick={async () => {
            setCurrentClueRow(record);
            handleUserFormType(1);
            handleCreateUserVisible(true);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部用户'}
        actionRef={actionRef}
        rowKey="unique"
        toolBarRender={() => [
          initialState?.currentUser?.userInfo?.role !== 'normal' ? (
            <>
              <Button
                key="2"
                type="primary"
                onClick={() => {
                  setInviteIdVisible(true);
                }}
              >
                邀请好友
              </Button>
              <Button
                key="3"
                type="primary"
                onClick={() => {
                  handleUserFormType(0);
                  handleCreateUserVisible(true);
                }}
              >
                创建用户
              </Button>{' '}
            </>
          ) : (
            ''
          ),
        ]}
        search={{
          labelWidth: 120,
          optionRender: ({ searchText, resetText }, {}) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
            ];
          },
        }}
        request={async (params: any) => {
          const rsp = await dyCpsUsers(params);
          if (rsp.code === 'SUCCESS') {
            setInviteId(rsp.data.inviteId);
            return {
              data: rsp.data.list,
              total: rsp.data.length,
            };
          }
        }}
        columns={columns}
      />
      <InviteFriendForm
        onSubmit={async (value) => {
          if (value) {
            message.success('复制成功~');
          } else {
            message.error('复制失败~');
          }
          setInviteIdVisible(false);
        }}
        onCancel={() => {
          setInviteIdVisible(false);
        }}
        updateModalVisible={inviteIdVisible}
        values={inviteId || {}}
      />
      <CreateUserDrawer
        onSubmit={async (value) => {
          // return;
          const success = await handleSaveUser({ ...value });
          if (success) {
            handleCreateUserVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleCreateUserVisible(false);
        }}
        updateModalVisible={createUserVisible}
        values={currentClueRow || {}}
        formType={userFormType}
      />
    </PageContainer>
  );
};
export default TableList;
